package work_pattern.rpc;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import work_pattern.Constant;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * RPC 客户端代码
 * client -> 消息 -> rpc_queue -> server -> 回调队列 -> 消息 -> client
 */
public class Client {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Channel channel = Constant.createChannel();
        channel.queueDeclare(Constant.RPC_QUEUE, true, false, false, null);
        String corrId = UUID.randomUUID().toString();
        // 定义回调队列
        String replayQueueName = channel.queueDeclare().getQueue(); // 定义临时队列，并返回生成的队列名称
        AMQP.BasicProperties properties = new AMQP.BasicProperties()
                .builder()
                .correlationId(corrId)
                .replyTo(replayQueueName)
                .build();
        String msg = "rpc...";
        // 使用内部交换机发送消息
        channel.basicPublish("", Constant.RPC_QUEUE, properties, msg.getBytes());
        System.out.println("rpc消息发送成功");
        BlockingQueue<String> responseQueue = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                if (properties.getCorrelationId().equals(corrId)) {
                    System.out.println("接收到回调消息: " + new String(body));
                    responseQueue.offer(new String(body, "UTF-8"));
                }
            }
        };
        channel.basicConsume(replayQueueName, true, consumer);
        // 获取回调结果
        System.out.println("rpc result: " + responseQueue.take());
    }
}
